package concurrency.chapter9;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author honway.liu
 * @date 2019-06-26 11:42
 * @email gm100861@gmail.com
 * @blog http://linuxsogood.org
 *
 * 每个对象都有一个wait set队列, 当调用wait()方法时,执行线程会进入到锁对象的Wait set队列中
 * 在执行notify()方法时, 在同一个锁的wait set队列中的线程,将会被唤醒,顺序不一定是FIFO
 * 当调用notify()的时候, 线程被唤醒,会重新去竟争锁,但是代码是从Wait()方法往后继续执行.wait()方法前的代码不会被执行
 */
public class WaitSetDemo {

    private static final byte[] LOCK = new byte[0];

    public static void main(String[] args) throws InterruptedException {
        IntStream.rangeClosed(1, 10).forEach( i -> {
            new Thread(() -> {
                synchronized (LOCK) {
                    System.out.println(i + " thread will be wait.");
                    try {
                        LOCK.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(i + " thread will leave.---");
                }
            }).start();
        });
        TimeUnit.SECONDS.sleep(1);
        IntStream.rangeClosed(1, 10).forEach( i -> {
            new Thread(() -> {
                synchronized (LOCK) {
                    System.out.println(i + " notify.");
                    LOCK.notify();
                }
            }).start();
        });
    }
}
